<!--
 * @author: Goalias
 * @since: 2025-01-10
-->
<script setup lang="ts">
import * as echarts from 'echarts/core';
import { TooltipComponent, LegendComponent } from 'echarts/components';
import { PieChart } from 'echarts/charts';
import { LabelLayout } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import { onMounted, onUnmounted, ref, watch } from 'vue';

echarts.use([
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer,
  LabelLayout
]);

const chartDom = ref<HTMLElement | null>(null);
let myChart: echarts.ECharts | null = null;


onMounted(() => {
  if (chartDom.value) {
    myChart = echarts.init(chartDom.value);
    const option = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        top: '5%',
        left: 'center'
      },
      animationDuration: 1000,
      animationDurationUpdate: 1000,
      series: [
        {
          name: props.name,
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 5
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 40,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: props.data
        }
      ]
    };
    myChart.setOption(option);

    
    watch(() => props?.data, (newData) => {
      updateChartData();
    });
  }
});


// 更新图表数据
const updateChartData = () => {
  if (myChart) {
    myChart.setOption({
      series: [
        {
          data: props.data
        }
      ]
    });
  }
};


const props = defineProps<{
  data: { value: number; name: string }[];
  name: string
  refreshTime: number
}>();

</script>

<template>
  <div class="pie-chart-container">
    <div ref="chartDom" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<style scoped>
.pie-chart-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
